const wechat = require("./wechat.js");
const toast = require("./toasts.js");
const utils = require("./utils.js");
const biz = require("./bizUtils.js");
const session = require("./session.js");

// 微信相关模块
// 模态窗
export const showModal = (options) => {
  return new Promise((resolve, reject) => {
    if (!options.isIt && resolve) {
      resolve();
      return;
    }


    utils.showModal();

    wx.showModal({
      title: options.title ? options.title : "提示",
      content: options.content,
      confirmText: options.confirmText ? options.confirmText : "确定",
      cancelText: options.cancelText ? options.cancelText : "取消",
      confirmColor: "#577bef",
      cancelColor: "#666666",
      showCancel: !options.hideCancel,
      success: (res) => {

        utils.hideModal();

        if (res.confirm) {
          resolve();
        } else {
          reject();
        };
      }
    })
  });
};

export const showBackModal = (options) => {
  showModal({
    title: options.title,
    content: options.content,
    hideCancel: true,
    isIt: (true)
  }).then(() => {
    wx.navigateBack({})
  }).catch(() => {});
};

export const openVipModal = (options) => {
  showModal({
    title: "VIP专属功能",
    content: options.content ? options.content : "开通VIP就可以使用专属功能",
    hideCancel: false,
    confirmText: "去开通",
    cancelText: "再想想",
    isIt: (true)
  }).then(() => {
    wx.navigateTo({
      url: '/pages/selectType/selectType',
    })
  }).catch(() => {});
};


// 拨打电话
export const makePhoneCall = (phone, success, fail) => {
  wx.makePhoneCall({
    phoneNumber: phone,
    success: function() {
      console.log('拨打成功');
      if (success) {
        success();
      }
    },
    fail: function() {
      console.log('拨打失败');
      if (fail) {
        fail();
      }
    }
  });
};

exports.commonShare = function(that) {
  var param = "";
  var user = that.data.user;
  if (!user) {
    user = session.getUserSync();
  }

  if (user) {
    if (user.sellerId == 1) {
      param = '&sourceType=SALES&sourceId=' + user.id;
    } else {
      param = '&sourceType=USER&sourceId=' + user.id;
    }
  }

  var suffix = parseInt(Math.random() * (12 - 1 + 1) + 1, 10);
  return {
    title: '2k学车，驾校学车价格全城最低，在线学车免费！',
    path: '/pages/index/index?type=share' + param,
    imageUrl: 'https://img.lingxing.site/jx/jx_banner3_1.png'
  }
}

exports.commonCardShare = function(that, obj) {
  if (!obj || !obj.sellerId) {
    return this.commonShare(that);
  }

  var t = biz.introTitle(obj);
  var query = "";
  if (obj.id != null) {
    query = query + "id=" + obj.id + "&";
  }

  var type = "SALES";
  if (obj.id != that.data.user.id) {
    type = 'USER';
  }
  var path = '/pages/cardDetail/cardDetail?from=share&sourceType=' + type + '&sourceId=' + that.data.user.id + '&type=share&' + query;

  return {
    title: t,
    path: path,
    imageUrl: obj.shareImg
  }
}

exports.commonCompanyShareWithUser = function(that, obj) {
  var com = {};
  com.id = obj.sellerId;
  com.mainBiz = obj.mainBiz;
  com.name = obj.company;
  com.shareImg = obj.companyShareImg;

  return this.commonCompanyShare(that, com);
}

exports.commonCompanyShare = function(that, obj) {

  var id = obj.id;
  var salesId = that.data.salesId;

  var mainBiz = '';
  if (obj.mainBiz) {
    mainBiz = ',主营业务' + obj.mainBiz;
  }

  // var t = obj.name + mainBiz + ',欢迎咨询';
  var t = '您好，这是我公司的微信官网，欢迎咨询';
  var query = "";
  if (id != null) {
    // query = query + "id=" + id + "&";
  }
  if (salesId != null) {
    query = query + "id=" + salesId + "&";
  }

  var type = "SALES";
  if (obj.id != that.data.user.sellerId) {
    type = 'USER';
  }

  return {
    title: t,
    path: '/pages/cardDetail/cardDetail?sourceType=' + type + '&sourceId=' + that.data.user.id + '&from=share&' + query,
    imageUrl: obj.shareImg
  }
}

exports.commonShopShare = function(that, obj) {

  var id = obj.id;
  var salesId = that.data.salesId;

  var mainBiz = '';
  if (obj.mainBiz) {
    mainBiz = ',主营业务' + obj.mainBiz;
  }

  var t = obj.name + mainBiz + ',欢迎光临';
  var query = "";
  if (id != null) {
    query = query + "id=" + id + "&";
  }
  if (salesId != null) {
    query = query + "salesId=" + salesId + "&";
  }

  var type = "SALES";
  if (obj.id != that.data.user.sellerId) {
    type = 'USER';
  }

  return {
    title: t,
    path: '/pages/shopDetail/shopDetail?sourceType=' + type + '&sourceId=' + that.data.user.id + '&from=share&' + query,
    imageUrl: obj.shareImg
  }
}

exports.baseShare = function(that, t, url, img) {

  var salesId = that.data.salesId;
  var query = "";

  if (salesId != null) {
    query = query + "salesId=" + salesId + "&";
  }

  var type = "USER";

  var user = that.data.user;
  if (!user) {
    user = session.getUserSync();
  }

  var sourceId = '';
  if (user) {
    sourceId = that.data.user.id;
    if (user.sellerId == 1) {
      type = 'SALES';
    }
  }

  return {
    title: t,
    path: url + '&sourceType=' + type + '&sourceId=' + sourceId + '&from=share&' + query,
    imageUrl: img
  }
}

exports.commonProductShare = function(that, obj, protype) {
  if (!obj) {
    return this.commonShare(that);
  }

  var t = obj.name;
  if (protype == 'cut') {
    t = "【砍价】小伙伴们快来帮我砍价，学车最低￥" + obj.minPrice + "，" + obj.name;
  } else if (protype == 'pt') {
    t = "【拼团】小伙伴们一起来拼团，原价￥" + obj.originalPrice + "，拼团价" + obj.discountPrice + "，" + obj.name;
  } else if (obj.discountPrice) {
    t = t + '原价' + obj.originalPrice + '折后' + obj.discountPrice;
  } else {
    t = t + '仅售' + obj.originalPrice;
  }

  var query = "";
  if (obj.id != null) {
    query = query + "id=" + obj.id + "&";
  }
  if (that.data.salesId != null) {
    query = query + "salesId=" + that.data.salesId + "&";
  }
  if (that.data.sellerId != null) {
    query = query + "sellerId=" + that.data.sellerId + "&";
  }

  var type = "SALES";
  if (obj.sellerId != that.data.user.sellerId) {
    type = 'USER';
  }

  var path = '/pages/productDetail/productDetail';
  if (protype == 'cut') {
    path = '/pages/cutDetail/cutDetail'
  }

  path = path + '?from=share&sourceType=' + type + '&sourceId=' + that.data.user.id + '&type=share&' + query;

  var cover1 = '';
  if (obj.cover) {
    cover1 = obj.cover.split(",")[0];
  }

  console.log(path);
  return {
    title: t,
    path: path,
    imageUrl: cover1
  }
}

exports.copy = function(str, msg) {
  if (!msg) {
    msg = '';
  }
  wx.setClipboardData({
    data: str,
    success: function(res) {
      wx.getClipboardData({
        success: function(res) {
          toast.show('已复制' + msg);
        }
      })
    }
  })
}


exports.gotoPage = function(that, e) {
  var url = e.currentTarget.dataset.url;
  var vip = e.currentTarget.dataset.vip;

  var user = that.data.user;
  if (!user.isVip && vip) {
    this.openVipModal({});
    return;
  }

  wx.navigateTo({
    url: url,
  })
}

exports.back = function (that) {
  var from = that.data.from;

  if(from == 'share') {
    wx.switchTab({
      url: '/pages/index/index',
    })
  } else {
    wx.navigateBack({
      
    })
  }
}

exports.auth = function(scope, success, fail) {
  wx.getSetting({
    success: (response) => {
      console.log(response)
      if (!response.authSetting[scope]) {
        wx.authorize({
          scope: scope,
          success: () => {
            if (success) {
              success();
            }
          },
          fail: (e) => {
            if (fail) {
              fail();
            }
          }
        })
      } else {
        if (success) {
          success();
        }
      }
    }
  })
}

exports.getLocation = function(that, success) {
  this.auth('scope.userLocation', function() {
    wx.getLocation({
      // type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success: function(res) {
        var lat = res.latitude //维度
        var lng = res.longitude //经度
        console.log(res);
        that.setData({
          lat: lat,
          lng: lng
        })
        if (success) {
          success();
        }
      }, 
      fail: function (res) {
        if (success) {
          success();
        }
      }
    });
  }, success);
}

exports.setTitle = function(that, title) {
  var nav = that.selectComponent('#nav')
  nav.setTitle(title);
}

exports.showTitle = function(that) {
  var nav = that.selectComponent('#nav')
  nav.show();
}

exports.hideTitle = function(that) {
  var nav = that.selectComponent('#nav')
  nav.hide();
}

exports.scroll = function(that, top) {
  var nav = that.selectComponent('#nav')
  nav.scroll(top);
}

exports.changeTab = function(that, index) {
  var tab = that.selectComponent('#tab')
  tab.changeTab(index);
}